package steak.xteamy.VoiceChat;

import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.function.LazyContainer;
import net.minecraft.util.Hand;
import net.minecraft.util.Identifier;
import net.minecraft.util.dynamic.Codecs;

import java.util.Optional;

public record FunctionComponent(String function, boolean mainHand) {

    public static final Codec<FunctionComponent> CODEC = RecordCodecBuilder.create(
            instance -> instance.group(
                    Codecs.NON_EMPTY_STRING.fieldOf("fuc").forGetter(FunctionComponent::function),
                    Codec.BOOL.fieldOf("main_hand").orElse(true).forGetter(FunctionComponent::mainHand)
            ).apply(instance, FunctionComponent::new)
    );

    public static final PacketCodec<RegistryByteBuf, FunctionComponent> PACKET_CODEC = PacketCodec.tuple(
            PacketCodecs.STRING,
            FunctionComponent::function,
            PacketCodecs.BOOL,
            FunctionComponent::mainHand,
            FunctionComponent::new
    );

    public void apply(MinecraftServer server, PlayerEntity user, Hand hand) {
        if (hand.equals(Hand.MAIN_HAND) == mainHand) {
            applyFunction(server, user);
        }
    }

    public void applyFunction(MinecraftServer server, PlayerEntity user) {
        if (server == null) return;

        Optional<Identifier> functionOptional = Optional.of(Identifier.of(function));
        functionOptional.map(LazyContainer::new).flatMap(function -> function.get(server.getCommandFunctionManager()))
                .ifPresent(function -> server.getCommandFunctionManager().execute(function, user.getCommandSource().withSilent().withLevel(2)));
    }
}
